package com.hzcx.app.simplechat.ui.friend;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.github.promeg.pinyinhelper.Pinyin;
import com.google.gson.Gson;
import com.hzcx.app.simplechat.R;
import com.hzcx.app.simplechat.base.BaseFragment;
import com.hzcx.app.simplechat.ui.chat.ChatGroupSettingActivity;
import com.hzcx.app.simplechat.ui.chat.GroupContactManageActivity;
import com.hzcx.app.simplechat.ui.chat.event.ChatFriendDeleteEvent;
import com.hzcx.app.simplechat.ui.friend.adapter.FriendAdapter;
import com.hzcx.app.simplechat.ui.friend.bean.FriendBean;
import com.hzcx.app.simplechat.ui.friend.bean.FriendCityBean;
import com.hzcx.app.simplechat.ui.friend.contract.FriendContract;
import com.hzcx.app.simplechat.ui.friend.event.AddFriendEvent;
import com.hzcx.app.simplechat.ui.friend.event.AddFriendSuccessEvent;
import com.hzcx.app.simplechat.ui.friend.event.DeleteFriendEvent;
import com.hzcx.app.simplechat.ui.friend.presenter.FriendPresenter;
import com.hzcx.app.simplechat.ui.home.AddFriendFirstActivity;
import com.hzcx.app.simplechat.ui.main.bean.FriendRequestCountBean;
import com.hzcx.app.simplechat.ui.main.event.NewFriendRequestEvent;
import com.hzcx.app.simplechat.ui.user.UserInfoActivity;
import com.hzcx.app.simplechat.util.PinyinUtil;
import com.hzcx.app.simplechat.util.empty.EmptyUtils;
import com.hzcx.app.simplechat.util.log.LogUtils;
import com.hzcx.app.simplechat.view.SideLetterBar;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.litepal.LitePal;
import org.litepal.crud.callback.FindMultiCallback;
import org.litepal.crud.callback.UpdateOrDeleteCallback;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 通讯录列表
 */
public class FriendFragment extends BaseFragment<FriendPresenter> implements FriendContract.View, OnRefreshListener, SideLetterBar.OnLetterChangedListener {
    @BindView(R.id.tv_friend_count)
    TextView tvFriendCount;
    @BindView(R.id.iv_friend_add)
    ImageView ivFriendAdd;
    @BindView(R.id.rv_friend)
    RecyclerView rvFriend;
    @BindView(R.id.smart_refresh)
    SmartRefreshLayout smartRefresh;
    @BindView(R.id.side_bar)
    SideLetterBar sideBar;
    @BindView(R.id.tv_overlay)
    TextView tvOverlay;

    private List<FriendBean> friendData;
    private FriendAdapter friendAdapter;

    @Override
    public int getLayout() {
        return R.layout.fragment_friend;
    }

    @Override
    public void initPresenter() {
        mPresenter = new FriendPresenter();
    }

    @Override
    public void initView() {

        smartRefresh.setOnRefreshListener(this);

        friendData = new ArrayList<>();
        friendAdapter = new FriendAdapter(friendData);
        rvFriend.setLayoutManager(new LinearLayoutManager(getActivity(), RecyclerView.VERTICAL, false));
        rvFriend.setAdapter(friendAdapter);

        sideBar.setOverlay(tvOverlay);

        sideBar.setOnLetterChangedListener(this);

        friendAdapter.setOnFriendListItemOnClickListener((headerPos, contentPos, id, bean) -> startActivity(new Intent(getActivity(), UserInfoActivity.class)
                .putExtra(UserInfoActivity.INTENT_USER_ID, id)));
    }

    @Override
    public void initData() {
        addHeaderView();

        LitePal.findAllAsync(FriendBean.class, true).listen(list -> {
            LogUtils.d(new Gson().toJson(list));
            if (list != null && list.size() >= 0) {
                friendData.clear();
                friendData.addAll(list);
                friendAdapter.notifyDataSetChanged();
            }
            mPresenter.getFriendList(getActivity());
        });
    }

    @OnClick({R.id.iv_friend_add, R.id.iv_friend_sort})
    public void viewOnClick(View view) {
        switch (view.getId()) {
            case R.id.iv_friend_add:
                startActivity(new Intent(getActivity(), AddFriendFirstActivity.class));
                break;

            case R.id.iv_friend_sort:
                startActivity(new Intent(getActivity(), FriendSortActivity.class));
                break;
        }
    }

    /**
     * 好友列表获取成功
     *
     * @param data
     */
    @Override
    public void friendListResult(List<FriendCityBean> data) {
//        try {
//            friendData.clear();
//            friendData.addAll(data);
//            friendAdapter.notifyDataSetChanged();
//            saveFriendDb(data);
//            int num = 0;
//            for (FriendBean bean : data) {
//                if (data == null || bean == null || bean.getCity() == null || bean.getCity().size() <= 0) {
//                    continue;
//                }
//                for (FriendCityBean subBean : bean.getCity()) {
//                    num++;
//                }
//            }
//            if (num > 0) {
//                tvFriendCount.setText("联系人(" + num + ")");
//            }
//
//            for (FriendBean bean : data) {
//                if (data == null || bean == null || bean.getCity() == null || bean.getCity().size() <= 0) {
//                    continue;
//                }
//                for (FriendCityBean subBean : bean.getCity()) {
//                    String pinyin = Pinyin.toPinyin(EmptyUtils.isNotEmpty(subBean.getRemarks_name()) ? subBean.getRemarks_name().charAt(0) : subBean.getNickname().charAt(0));
//                    LogUtils.i(pinyin + "    " + PinyinUtil.isPinyin(pinyin.charAt(0)));
//                }
//            }
//
//        } catch (Exception e) {
//            e.printStackTrace();
//        }

        new Thread(() -> {
            try {
                // 先设置每个用户的拼音，然后根据拼音排序
                for (FriendCityBean bean : data) {
                    String pinyin = Pinyin.toPinyin(EmptyUtils.isNotEmpty(bean.getRemarks_name()) ? bean.getRemarks_name() : bean.getNickname(), "");
                    bean.setPinyin(pinyin.toUpperCase());
                }
                // 排序
                PinyinUtil.transferList(data);
                // 排序成功后，整合数据
                // 先添加字幕列表数据
                List<FriendBean> list = new ArrayList<>();
                for (FriendCityBean bean : data) {
                    boolean isAdd = true;
                    for (FriendBean subBean : list) {
                        if (subBean.getName().equals(PinyinUtil.isPinyin(bean.getPinyin().charAt(0)))) {
                            isAdd = false;
                            break;
                        }
                    }
                    if (isAdd) {
                        FriendBean friendBean = new FriendBean();
                        friendBean.setName(PinyinUtil.isPinyin(bean.getPinyin().charAt(0)));
                        List<FriendCityBean> cityBeanList = new ArrayList<>();
                        friendBean.setCity(cityBeanList);
                        list.add(friendBean);
                    }
                }
                // 在添加好友数据
                for (FriendCityBean cityBean : data) {
                    for (int i = 0; i < list.size(); i++) {
                        if (PinyinUtil.isPinyin(cityBean.getPinyin().charAt(0)).equals(list.get(i).getName())) {
                            if (list.get(i).getCity() == null) {
                                List<FriendCityBean> cityBeanList = new ArrayList<>();
                                list.get(i).setCity(cityBeanList);
                            }
                            list.get(i).getCity().add(cityBean);
                        }
                    }
                }
                Message msg = new Message();
                msg.what = 0x01;
                msg.obj = list;
                msg.arg1=data.size();
                handler.sendMessage(msg);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 0x01) {
                smartRefresh.finishRefresh();
                List<FriendBean> data= (List<FriendBean>) msg.obj;
                friendData.clear();
                friendData.addAll(data);
                friendAdapter.notifyDataSetChanged();
                saveFriendDb(data);
                tvFriendCount.setText("联系人(" + msg.arg1 + ")");

                // 改变右侧字母选项
                List<String> list=new ArrayList<>();
                list.add("↑");
                for (FriendBean bean:friendData){
                    list.add(bean.getName());
                }
                String[] toBeStored = list.toArray(new String[list.size()]);
                sideBar.setContent(toBeStored);
            }
        }
    };

    /**
     * 保存好友缓存数据
     */
    private void saveFriendDb(List<FriendBean> data) {
        if (data == null || data.size() <= 0) {
            return;
        }
        LitePal.deleteAllAsync(FriendCityBean.class).listen(rowsAffected -> LitePal.deleteAllAsync(FriendBean.class).listen(rowsAffected1 -> {
            for (int i = 0; i < data.size(); i++) {
                if (data.get(i) == null) {
                    continue;
                }
                data.get(i).save();
                if (data.get(i).getCity() == null || data.get(i).getCity().size() <= 0) {
                    continue;
                }
                for (int j = 0; j < data.get(i).getCity().size(); j++) {
                    data.get(i).getCity().get(j).save();
                }
            }
        }));
    }

    @Override
    public void onFail() {
        smartRefresh.finishRefresh();
    }

    /**
     * 好友请求新消息条数获取成功
     *
     * @param data
     */
    @Override
    public void friendRequestCountResult(FriendRequestCountBean data) {
        if (tv_request_count == null) {
            return;
        }
        if (data.getBuddy_count() <= 0) {
            return;
        }
        tv_request_count.setText(data.getBuddy_count() + "");
        tv_request_count.setVisibility(View.VISIBLE);
    }

    /**
     * 刷新
     *
     * @param refreshLayout
     */
    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        mPresenter.getFriendList(getActivity());
    }

    /**
     * 添加头部
     */
    private LinearLayout ll_new_list, ll_chat_group, ll_chat_lable;
    private TextView tv_request_count;
    private ConstraintLayout cons_search;

    private void addHeaderView() {
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.layout_friend_header, null);
        ll_new_list = view.findViewById(R.id.ll_new_list);
        tv_request_count = view.findViewById(R.id.tv_request_count);
        cons_search = view.findViewById(R.id.cons_search);
        ll_chat_lable = view.findViewById(R.id.ll_chat_lable);
        ll_chat_group = view.findViewById(R.id.ll_chat_group);

        ll_new_list.setOnClickListener(view1 -> {
            tv_request_count.setVisibility(View.GONE);
            startActivity(new Intent(getActivity(), FriendRequestActivity.class));
        });

        ll_chat_lable.setOnClickListener(view13 -> startActivity(new Intent(getActivity(), FriendLableListActivity.class)));

        ll_chat_group.setOnClickListener(view13 -> startActivity(new Intent(getActivity(), GroupContactManageActivity.class)));


        cons_search.setOnClickListener(view12 -> startActivity(new Intent(getActivity(), FriendSearchActivity.class)
                .putExtra(FriendSearchActivity.INTENT_TAG, 1)));

        friendAdapter.addHeaderView(view);
        mPresenter.getFriendRequestCount(getActivity());
    }

    /**
     * 根据字母展示不同位置
     *
     * @param letter
     */
    @Override
    public void onLetterChanged(String letter) {
        if (letter.equals("↑")) {
            rvFriend.scrollToPosition(0);
            return;
        }
        for (int i = 0; i < friendData.size(); i++) {
            if (friendData.get(i) == null) {
                continue;
            }
            if (EmptyUtils.isEmpty(friendData.get(i).getName())) {
                continue;
            }
            if (letter.equals(friendData.get(i).getName())) {
                ((LinearLayoutManager) rvFriend.getLayoutManager()).scrollToPositionWithOffset(i+1, 0);
                break;
            }
        }
    }

    /**
     * 添加好友成功
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void addFriendSuccess(AddFriendSuccessEvent event) {
        smartRefresh.autoRefresh();
    }

    /**
     * 收到新的好友请求
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void newRequest(NewFriendRequestEvent event) {
        if (event.getCount() <= 0) {
            return;
        }
        tv_request_count.setText(event.getCount() + "");
        tv_request_count.setVisibility(View.VISIBLE);
    }

    /**
     * 对方同意好友请求，刷新列表
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refreshFriend(AddFriendEvent event) {
        mPresenter.getFriendList(getActivity());
    }

    /**
     * 后台通知的删除好友
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void deleteFriendByService(ChatFriendDeleteEvent event) {
        mPresenter.getFriendList(getActivity());
    }

    /**
     * 删除好友，刷新列表
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void deleteFriend(DeleteFriendEvent event) {
        mPresenter.getFriendList(getActivity());
    }
}
